<template>
    <div class="accountList">
        <div class="header flexbetween" style="margin-bottom: 20px">
            <div></div>
            <div class="iconBtn">
                <el-tooltip effect="light" content="添加账号" placement="top" :enterable="false" v-if="menuAuthCodes.includes('M112')">
                    <span class="iconfont icon-tianjia" @click="addAccount"></span>
                </el-tooltip>
            </div>
        </div>
        <element-table :data="accountList" :columns="cloumns" :loading="tableLoading" :tableHeight="tableHeight" :pageNo="pageNo"
                       :pageSize="pageSize" :total="total" @changePageNo="changePageNo" @changePageSize="changePageSize">
        </element-table>

        <!-- 添加、编辑账号信息 -->
        <el-dialog :visible="accountVisible" :title="editTitle" width="640px" class="addAccount" @close="cancel">
            <el-form ref="accountForm" :model="accountForm" :rules="accountRules" label-width="130px">
                <el-form-item label="账号" prop="account">
                    <el-input v-model="accountForm.account" size="small" :disabled="dialogType == 'edit'"></el-input>
                </el-form-item>
                <el-form-item label="名称" prop="userName">
                    <el-input v-model="accountForm.userName" size="small"></el-input>
                </el-form-item>
                <el-form-item label="角色" prop="roleIds">
                    <a-select v-model="accountForm.roleIds" style="width: 100%" mode="multiple" :disabled="isSuperAdmin">
                        <a-select-option v-for="role in rolesLists" :key="role.id" :value="role.id">
                            {{ role.roleName }}
                        </a-select-option>
                    </a-select>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="accountForm.mobile" size="small"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="accountForm.email" size="small"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password" v-if="dialogType=='add'">
                    <el-input v-model="accountForm.password" size="small" type="password"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword" v-if="dialogType=='add'">
                    <el-input v-model="accountForm.confirmPassword" size="small" type="password"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" type="text" @click="cancel">取消</el-button>
                <el-button type="primary" size="small" @click="submit">保存</el-button>
            </span>
        </el-dialog>

        <!-- 重置密码 -->
        <el-dialog :visible="passwordVisible" title="更改客服密码" width="640px" class="addAccount" @close="passCancel">
            <el-form ref="passForm" :model="passForm" :rules="passRules" label-width="130px">
                <el-form-item label="账号">
                    <el-input v-model="passForm.account" size="small" disabled></el-input>
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                    <el-input v-model="passForm.newPassword" size="small" type="password"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                    <el-input v-model="passForm.confirmPassword" size="small" type="password"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" type="text" @click="passCancel">取消</el-button>
                <el-button type="primary" size="small" @click="passSubmit">保存</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import elementTable from "@/components/elementTable";
import { queryList, getRolesList, addUser, updateUser, removeUser, updateUserStatus, resetPassword } from "@/api/systemConfig";
export default {
    name: "accountList",
    data() {
        var checkPhone = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('请输入手机号'));
            }
            const regex = /^1[3456789]\d{9}$/;
            if (!regex.test(value)) {
                callback(new Error('请输入正确的手机格式'));
            } else { callback() }
        }
        var checkEmail = (rule, value, callback) => {
            if (value) {
                const regex = /^(\w-*\.*\_*)+@(\w-?)+(\.\w{2,})+$/;
                if (!regex.test(value)) {
                    callback(new Error('请输入正确的邮箱格式'));
                } else { callback() }
            } else {
                callback();
            }
        }
        var checkPass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'));
            } else if (value !== this.accountForm.password) {
                callback(new Error('两次输入密码不一致!'));
            } else {
                callback();
            }
        }
        var checkPass2 = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'));
            } else if (value !== this.passForm.newPassword) {
                callback(new Error('两次输入密码不一致!'));
            } else {
                callback();
            }
        }
        return {
            dialogType: "add",
            editTitle: "添加账号",
            editId: "",
            accountVisible: false,
            passwordVisible: false,
            accountList: [],
            tableLoading: false,
            pageNo: 1,
            pageSize: 10,
            total: 0,
            accountForm: {
                account: "",
                userName: "",
                roleIds: [],
                mobile: "",
                email: "",
                password: "",
                confirmPassword: ""
            },
            accountRules: {
                account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
                userName: [{ required: true, message: '请输入名称', trigger: 'blur' }],
                roleIds: [{ required: true, message: '请选择角色', trigger: 'blur' }],
                mobile: [{ required: true, validator: checkPhone, trigger: 'blur' }],
                email: [{ validator: checkEmail, trigger: 'blur' }],
                password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
                confirmPassword: [{ required: true, validator: checkPass, trigger: 'blur' }],
            },
            passForm: {
                account: "",
                newPassword: "",
                confirmPassword: ""
            },
            passRules: {
                newPassword: [{ required: true, message: '请输入密码', trigger: 'blur' }],
                confirmPassword: [{ required: true, validator: checkPass2, trigger: 'blur' }],
            },
            cloumns: [
                {
                    config: {
                        label: "账号",
                        prop: "account"
                    },
                },
                {
                    config: {
                        label: "名称",
                        prop: "userName"
                    },
                },
                {
                    config: {
                        label: "角色",
                    },
                    render: (h, scope) => {
                        var roleNames = scope.roleNames != null ? scope.roleNames.join("; ") : "";
                        return (<span>{roleNames}</span>)
                    }
                },
                {
                    config: {
                        label: "手机号",
                        prop: "mobile"
                    },
                },
                {
                    config: {
                        label: "坐席状态",
                    },
                    render: (h, scope) => {
                        var status = scope.status == 0 ? "禁用" : scope.status == 1 ? "启用" : "锁定";
                        return (<span>{status}</span>)
                    }
                },
                {
                    config: {
                        label: "创建时间",
                        prop: "createTime"
                    }
                },
                {
                    config: {
                        label: "操作",
                        width: "180"
                    },
                    render: (h, scope) => {
                        var text = scope.status == 0 ? "启用" : scope.status == 1 ? "禁用" : "";
                        var myClass = scope.status == 0 ? "icon-qiyong" : scope.status == 1 ? "icon-hulve" : "none";
                        return (
                            <div class="operation">
                                <el-tooltip effect="light" content="编辑" placement="top" enterable={false}
                                    v-show={this.menuAuthCodes.includes('M113')}>
                                    <span class="iconfont icon-bianjidaan" onClick={() => this.editAccount(scope)}></span>
                                </el-tooltip>
                                <el-tooltip effect="light" content="删除" placement="top" enterable={false}
                                    v-show={this.menuAuthCodes.includes('M114')}>
                                    <span class="iconfont icon-shanchu" onClick={() => this.delAccount(scope.id)}></span>
                                </el-tooltip>
                                <el-tooltip effect="light" content={text} placement="top" enterable={false}
                                    v-show={this.menuAuthCodes.includes('M115')}>
                                    <span class={["iconfont", myClass]} onClick={() => this.editStatus(scope)}></span>
                                </el-tooltip>
                                <el-tooltip effect="light" content="重置密码" placement="top" enterable={false}
                                    v-show={this.menuAuthCodes.includes('M116')}>
                                    <span class="iconfont icon-zhongzhimima" onClick={() => this.editPassword(scope)}></span>
                                </el-tooltip>
                            </div>
                        );
                    },
                },
            ],
            rolesList: [],
            isSuperAdmin: false,
            superAdminRole: [],
        }
    },
    methods: {
        //获取账号列表
        getAccountList() {
            if (!this.menuAuthCodes.includes("M111")) {
                return;
            }
            this.tableLoading = true;
            var param = {
                pageNo: this.pageNo,
                pageSize: this.pageSize,
            }
            queryList(param).then((resp) => {
                this.tableLoading = false;
                if (resp.status == 0) {
                    this.total = resp.data.total;
                    this.accountList = resp.data.records || [];
                } else {
                    this.$antMessage.warning(resp.message);
                }
            });
        },
        //获取角色列表
        getRolesList() {
            getRolesList().then(resp => {
                if (resp.status == 0) {
                    this.rolesList = resp.data;
                }
            });
        },
        //添加账号
        addAccount() {
            this.dialogType = "add";
            this.editTitle = "添加账号";
            this.accountVisible = true;
        },
        //编辑账号
        editAccount(data) {
            if (!this.menuAuthCodes.includes("M113")) {
                return;
            }
            this.isSuperAdmin = data.isSuperAdmin == 1;
            if (this.isSuperAdmin) {
                this.superAdminRole = [{ id: data.roleIds[0], roleName: data.roleNames[0] }];
            }
            var arr = ["account", "userName", "roleIds", "mobile", "email"];
            arr.forEach((item) => {
                this.$set(this.accountForm, item, data[item]);
            });
            this.dialogType = "edit";
            this.editId = data.id;
            this.editTitle = "账号编辑";
            this.accountVisible = true;
        },
        //删除账号
        delAccount(id) {
            if (!this.menuAuthCodes.includes("M114")) {
                return;
            }
            this.$confirm("是否确定删除?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                removeUser({ id }).then((resp) => {
                    if (resp.status == 0) {
                        this.pageNo = 1;
                        this.getAccountList();
                        this.$antMessage.success("删除成功");
                    } else {
                        this.$antMessage.warning(resp.message);
                    }
                });
            }).catch(() => { });
        },
        //添加、编辑账号提交
        submit() {
            this.$refs.accountForm.validate((valid) => {
                if (valid) {
                    if (this.dialogType == "add") {
                        var param = Object.assign({}, this.accountForm);
                        addUser(param).then(resp => {
                            if (resp.status == 0) {
                                this.pageNo = 1;
                                this.getAccountList();
                                this.cancel();
                                this.$antMessage.success("添加成功");
                            } else {
                                this.$antMessage.warning(resp.message);
                            }
                        });
                    } else {
                        var param = {
                            id: this.editId,
                            userName: this.accountForm.userName,
                            roleIds: this.accountForm.roleIds,
                            mobile: this.accountForm.mobile,
                            email: this.accountForm.email,
                        }
                        updateUser(param).then(resp => {
                            if (resp.status == 0) {
                                this.getAccountList();
                                this.cancel();
                                this.$antMessage.success("编辑成功");
                            } else {
                                this.$antMessage.warning(resp.message);
                            }
                        });
                    }
                }
            });
        },
        cancel() {
            this.$set(this.accountForm, "account", "");
            this.$set(this.accountForm, "userName", "");
            this.$set(this.accountForm, "roleIds", []);
            this.$set(this.accountForm, "mobile", "");
            this.$set(this.accountForm, "email", "");
            this.$set(this.accountForm, "password", "");
            this.$set(this.accountForm, "confirmPassword", "");
            this.accountVisible = false;
        },
        editPassword(data) {
            if (!this.menuAuthCodes.includes("M116")) {
                return;
            }
            this.editId = data.id;
            this.passForm.account = data.account;
            this.passwordVisible = true;
        },
        passSubmit() {
            this.$refs.passForm.validate((valid) => {
                if (valid) {
                    var param = {
                        id: this.editId,
                        newPassword: this.passForm.newPassword,
                        confirmPassword: this.passForm.confirmPassword,
                    }
                    resetPassword(param).then(resp => {
                        if (resp.status == 0) {
                            this.passCancel();
                            this.$antMessage.success("重置密码成功");
                        } else {
                            this.$antMessage.warning(resp.message);
                        }
                    });
                }
            });
        },
        passCancel() {
            this.$refs.passForm.resetFields();
            this.passwordVisible = false;
        },
        editStatus(data) {
            if (!this.menuAuthCodes.includes("M115")) {
                return;
            }
            var param = {
                id: data.id,
                status: data.status == 0 ? 1 : 0
            }
            updateUserStatus(param).then(resp => {
                if (resp.status == 0) {
                    this.getAccountList();
                    this.$antMessage.success("操作成功");
                } else {
                    this.$antMessage.warning(resp.message);
                }
            });
        },
        changePageSize(val) {
            this.pageSize = val;
            this.getAccountList();
        },
        changePageNo(val) {
            this.pageNo = val;
            this.getAccountList();
        },
    },
    created() {
        this.getAccountList();
        this.getRolesList();
    },
    computed: {
        tableHeight() {
            return document.body.clientHeight - 300;
        },
        rolesLists() {
            return this.isSuperAdmin ? this.superAdminRole : this.rolesList;
        }
    },
    components: {
        elementTable
    }
}
</script>

<style lang="scss">
.accountList {
    .ant-select-selection--multiple {
        height: 34px;
        overflow-y: scroll;
    }
    .addAccount {
        .el-dialog__body {
            padding-top: 60px;
            overflow: hidden;
            .el-form-item__content {
                width: 400px;
            }
        }
    }
    .none {
        display: none;
    }
}
</style>